from fastapi import APIRouter, HTTPException, status, Body
from typing import Optional
import uuid
from datetime import datetime, timedelta
import sys
from pathlib import Path

# Add parent directories to path
sys.path.append(str(Path(__file__).parent.parent.parent))

from config.settings import settings
from src.models.classroom import ClassroomRequest, ClassroomResponse, ApprovalRules, ApprovalStatus
from src.models.base import BaseResponse
from src.models.audit_models import AuditRequest
from src.modules.classroom_audit import AuditWorkflowManager, AuditStrategy
from src.modules.simple_rules import SimpleRuleEngine
from src.utils.logger import get_logger

router = APIRouter(prefix="/api/v1/classroom", tags=["教室借用审核"])
logger = get_logger(__name__)


@router.post("/apply", response_model=ClassroomResponse)
async def submit_classroom_application(application: ClassroomRequest):
    """提交教室借用申请."""
    
    try:
        # 生成申请ID
        request_id = str(uuid.uuid4())
        
        logger.info(f"收到教室借用申请: {request_id}, 申请人: {application.applicant_name}")
        
        # 转换为审核请求格式
        audit_request = _convert_to_audit_request(application, request_id)
        
        # 获取审核工作流
        workflow_manager = AuditWorkflowManager()
        workflow = workflow_manager.get_workflow()
        
        # 执行标准审核流程
        audit_result = await workflow.audit_request(
            audit_request,
            strategy=AuditStrategy.STANDARD,
            original_request=application
        )
        
        # 转换审核结果为响应格式
        response = _convert_audit_result_to_response(audit_result, request_id)
        
        logger.info(f"申请审核完成: {request_id}, 状态: {response.status}, 评分: {response.approval_score}")
        return response
        
    except Exception as e:
        logger.error(f"教室申请处理失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"申请处理失败: {str(e)}"
        )


@router.get("/rules", response_model=BaseResponse)
async def get_default_rules():
    """获取默认的审核规则."""
    return BaseResponse(
        success=True,
        message="获取默认审核规则成功",
        data={
            "default_rules": settings.default_approval_rules,
            "rules_description": "这是系统默认的教室借用审核标准，用户可以提供自定义规则覆盖"
        }
    )


@router.post("/rules/validate", response_model=BaseResponse)
async def validate_approval_rules(rules: ApprovalRules):
    """验证审核规则格式."""
    try:
        # 这里可以添加规则格式验证逻辑
        rules_length = len(rules.rules_text)
        
        return BaseResponse(
            success=True,
            message="审核规则验证成功",
            data={
                "rules_length": rules_length,
                "strict_mode": rules.strict_mode,
                "auto_approve_threshold": rules.auto_approve_threshold,
                "auto_reject_threshold": rules.auto_reject_threshold,
                "validation_status": "有效"
            }
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"规则验证失败: {str(e)}"
        )


@router.get("/application/{request_id}")
async def get_application_status(request_id: str):
    """根据申请ID查询申请状态."""
    # 这里将来会从数据库查询
    # 目前返回模拟数据
    return BaseResponse(
        success=True,
        message="查询成功",
        data={
            "request_id": request_id,
            "status": "审核中",
            "submitted_at": datetime.now().isoformat(),
            "message": "申请正在处理中，请稍后查询结果"
        }
    )


def _convert_to_audit_request(application: ClassroomRequest, request_id: str) -> AuditRequest:
    """将教室申请转换为审核请求格式."""
    
    # 组装申请人信息（基于用户实际提供的信息）
    applicant_info = {
        "name": application.applicant_name,
        "type": application.user_category,  # 添加必要的type字段
        "user_category": application.user_category,
        "borrow_type": application.borrow_type,
        "borrow_category": application.borrow_category
    }
    
    # 使用未来时间作为占位符，实际时间信息在time_description中
    future_time = datetime.now() + timedelta(hours=24)  # 确保是明显的未来时间
    
    # 创建审核请求
    audit_request = AuditRequest(
        request_id=request_id,
        applicant_info=applicant_info,
        classroom_id=application.classroom_name,  # 使用具体的教室名称
        start_time=future_time,  # 占位符，实际信息在time_description
        end_time=future_time + timedelta(hours=2),    # 占位符，实际信息在time_description
        usage_purpose=application.application_description,
        participants_count=1,  # 默认最少1人，AI会从描述中推断实际人数
        equipment_needs=[application.equipment_description] if application.need_equipment and application.equipment_description else [],
        additional_notes=f"申请概述: {application.description}\n教师信息: {application.teacher_name} ({application.teacher_email})\n房间信息: {application.room_info}\n时间描述: {application.time_description}\n申请材料: {application.application_materials or '无'}",
        supporting_documents=[]
    )
    
    return audit_request


def _convert_audit_result_to_response(audit_result, request_id: str) -> ClassroomResponse:
    """将审核结果转换为响应格式."""
    
    # 转换审核决策为审批状态
    decision_map = {
        "approved": ApprovalStatus.APPROVED,
        "rejected": ApprovalStatus.REJECTED,
        "conditional": ApprovalStatus.APPROVED,  # 条件审批当作通过
        "pending": ApprovalStatus.PENDING
    }
    
    status_result = decision_map.get(audit_result.decision.value, ApprovalStatus.PENDING)
    
    # 生成审核原因
    approval_reason = " | ".join(audit_result.reasons) if audit_result.reasons else "审核完成"
    
    # 提取风险因素
    risk_factors = []
    if audit_result.ai_analysis and audit_result.ai_analysis.risk_assessment:
        risk_factors = audit_result.ai_analysis.risk_assessment.get("risk_factors", [])
    
    # 生成建议
    recommendations = []
    if status_result == ApprovalStatus.APPROVED:
        recommendations = ["请按时使用教室", "使用后请及时清理", "如有设备问题请联系管理员"]
    else:
        recommendations = ["请完善申请材料", "如有疑问请联系审核人员"]
    
    return ClassroomResponse(
        request_id=request_id,
        status=status_result,
        approval_reason=approval_reason,
        approval_score=audit_result.final_score,
        risk_factors=risk_factors,
        recommendations=recommendations
    )